<template>
    <div class="app-container">
        <el-form :model="subject" :rules="rules" ref="ruleForm" label-width="200px" class="demo-ruleForm">
            <el-form-item label="科目" prop="subjectName" >
                <el-input v-model="subject.subjectName"></el-input>
            </el-form-item>
            <el-form-item label="排序编码" prop="orderNum" >
                <el-input v-model="subject.orderNum"></el-input>
            </el-form-item>
            <el-form-item label="所属年级" prop="gradeId" >
                <el-select v-model="subject.gradeId" placeholder="请选择">
                  <el-option
                    v-for="item in grades"
                    :key="item.id"
                    :label="item.gradeName"
                    :value="item.id">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
                <el-button @click="returnPage()">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
    
</template>

<script>
import { addSubjectApi } from "@/api/subject"
import { getAllGradesApi } from "@/api/grade"
  export default {
    data() {
      return {
        subject: {},
        grades: [],
        rules: {
        }
      }
    },
    created() {
      getAllGradesApi().then(response => {
        this.grades = response.data
      })
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var formdata = new FormData()
            Object.keys(this.subject).forEach(key => {
              formdata.append(key, this.subject[key])
            })
            addSubjectApi(formdata).then(response => {
              if(response.status == 0){
                this.$message('提交成功')
              }
              this.$router.push('/content/subject')
            })
          } 
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      returnPage() {
        if (window.history.length <= 1) {
          this.$router.push({ path: "/zh-CN/home" });
          return false;
        } else {
          this.$router.go(-1);
        }
      }
    }
  }
</script>